<template>
	<view class="relative full-screen">
		<uni-nav-bar ref="navBar" fixed statusBar :border="false" backgroundColor="white" @clickLeft="goBack">
			<template v-slot:left>
				<image class="size-32" src="@/static/svg/icon-back.svg" />
			</template>
			<view class="flex center w-full fs-16 text-black text-color-regular">我的活动</view>
		</uni-nav-bar>
		<z-paging ref="paging" :fixed="false" :paging-style="{height: `calc(100vh - ${navBarHeight || 0}px)`}"  v-model="dataList" @query="queryList">
			<template v-slot:top>
				<view class="bg-white">
					<search-bar v-model="queryParams.activeTitle" @search="onSearch" @clean="onClean" placeholder="搜索活动名称"></search-bar>
					<view class="tabs px-16">
						<view v-for="(tab,i) in tabs" :key="i" class="tab flex-1" @click="onTabClick(tab)">
							<text :class="currentTab===tab.value?'active text-color-regular fs-16':'text-color-hint fs-15'">{{tab.title}}</text>
						</view>
					</view>
				</view>
			</template>
			<view v-for="(item, i) in dataList" :key="i" class="uni-bg-color px-16 pt-16">
				<ActivityItem :data="item" @onDelete="onDelete(i)" />
			</view>
		</z-paging>
	</view>
</template>

<script setup name="MyActivity">
	import { onShareAppMessage, onBackPress, onLoad,onShow } from '@dcloudio/uni-app'
	import { onMounted, ref, unref, computed, onBeforeUnmount } from 'vue'
	import { getMyActiveApi } from '@/api/business.js'
	import ActivityItem from './components/ActivityItem.vue'
	
	const deviceBack = ref(true) // 设备返回键或屏幕左滑返回
	const goBack = () => {
		deviceBack.value = false
		const pages = getCurrentPages()
		console.log('点击返回', from.value, pages)
		const num = pages.length // 当前页面栈总数
		let backNum // 需要返回的页数
		for (let i = 0; i < num; i++) {
			if (pages[i].route === 'pagesB/my-activity/my-activity') {
				backNum = num - i - 1
				break
			}
		}
		console.log('需要返回的页面数', backNum)
		uni.navigateBack({
			delta: backNum
		})
	}
	const from = ref('')
	
	onBeforeUnmount(() => {
		console.log('页面关闭', deviceBack.value, from.value)
		if (deviceBack.value) {
			goBack()
		}
	})
	
	const navBar = ref(null)
	const navBarHeight = computed(() => {
		const statusBarHeight = uni.getWindowInfo().statusBarHeight
		const navigationBarHeight = statusBarHeight + (navBar.value && navBar.value.height || 0)
		return navigationBarHeight
	})

	const tabs = [
		{ title: '全部', value: '' },
		{ title: '未开始', value: 2 },
		{ title: '进行中', value: 3 },
		{ title: '已结束', value: 4 },
		{ title: '未发布', value: 1 },
	]
	
	const currentTab = ref('')
	const firstInfo = ref(true)
	const onTabClick = (tab) => {
		if (currentTab.value !== tab.value) {
			currentTab.value = tab.value
			queryParams.value.activeState = tab.value
			paging.value.reload()
		}
	}
	
	const dataList = ref([])
	const paging = ref(null)
	const queryParams = ref({
		activeTitle: '',
		activeState: '', // 活动状态（1-未发布，2-未开始，3-进行中，4-已结束）
		pageNum: 1,
		pageSize: 20,
	})
	const queryList = (pageNo, pageSize) => {
		firstInfo.value = false
		queryParams.value.pageNum = pageNo
		getMyActiveApi(unref(queryParams)).then(res => {
			paging.value.complete(res.list)
		})
	}
	
	const onSearch = () => {
		queryParams.value.pageNum = 1
		paging.value.reload()
	}
	
	const onClean = () => {
		queryParams.value.activeTitle = ''
		queryParams.value.pageNum = 1
		dataList.value = []
		paging.value.reload()
	}
	
	const onDelete = (i) => {
		dataList.value.splice(i, 1)
		paging.value.reload()
	}
	
	onShareAppMessage((options) => {
		console.log('我的分享', options)
		const activeId = options.target.dataset.activityId;
		const target = dataList.value.find(item=>item.id===activeId);
		const url = target?.promotionType==='GROUP_BUY'
				?`/pagesB/activity/activity-group-buy`
				:`/pagesB/activity/activity`;
		return {
			title: options.target.dataset.title,
			path: `${url}?id=${activeId}&_from=BMyActivity`,
			imageUrl: options.target.dataset.filepath
		}
	})
	
	// 活动详情
	const onDeleteSuccess = (id) => {
		const index = dataList.value.findIndex(it => it.id == id)
		if (index !== -1) {
			dataList.value.splice(index, 1)
		}
	}
	
	const refresh = () => {
		console.log('页面刷新', paging.value)
		if (paging.value) {
			onSearch()
		}
	}
	onShow((options) => {
		// console.log('show',options,firstInfo.value)
		if(!firstInfo.value){
			refresh()
		}
	})
	onBackPress((options) =>{
		console.log(options,'onBackPress')
		refresh()
	})
	onMounted(() => {
		uni.$on('deleteActivitySuccess', onDeleteSuccess)
	})
	onLoad((options) => {
		console.log('我的活动', options)
		from.value = options.from
	})
	defineExpose({
		refresh
	})
</script>

<style lang="scss" scoped>
	.tabs {
		height: 30px;
		display: flex;
		align-items: center;

		.tab {
			display: inline-flex;
			height: 100%;
			
			.active {
				position: relative;
				
				&::after {
					content: '';
					position: absolute;
					bottom: 0;
					left: 15%;
					height: 4px;
					width: 70%;
					border-radius: 4px;
					background: $uni-primary;
				}
			}
		}
	}
</style>
